<?php
include_once("functions/db_manipulate.php");

if (!init()) {
    redirect("login.php");
    exit();
}

?>

    <meta charset="UTF-8">
<?php

$uploaddir = $_SERVER['DOCUMENT_ROOT'] . '/news_img/'; //Change fly-fishing-forum to the site name

$acceptedFormats = array('gif', 'png', 'jpg', 'jpeg');


connectDB();

startTransaction();

$timeStamp = getLocalTimeStamp();

$insertFlyResultSet = mysql_query("INSERT INTO news(header, content, author, date, time)
VALUES ('" . mysql_real_escape_string($_POST['header']) . "',
        '" . mysql_real_escape_string($_POST['content']) . "',
        '" . $_SESSION['aid'] . "',
        '" . mysql_real_escape_string(f_Date($timeStamp)) . "',
        '" . mysql_real_escape_string(f_Time($timeStamp)) . "')") or die(mysql_error());

$idNews = mysql_insert_id();

$mainImgInsertResultSet = null;
$imgInsertResultSet = null;

if (isset($_FILES['image'])) {

    $uploadfile = '';

    if (in_array(strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)), $acceptedFormats)) {
        $file = date("dmY") . "_" . date("GHi") . getFormattedTime() . "_main_news_img" . "." . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $uploadfile = $uploaddir . $file;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {

            $mainImgInsertResultSet = mysql_query("INSERT INTO newsimages(path, newsid, main) VALUES ('" . mysql_real_escape_string($file) . "', '" . mysql_real_escape_string($idNews) . "', '1')") or die(mysql_error());
        } else echo $_FILES['image']['error'];
    } else echo "Main Image" . "<br>";
}


if (isset($_FILES['images'])) {

    $i = 0;
    $uploadfile = '';

    while (isset($_FILES['images']['name'][$i]) && $i < 5) {

        if (in_array(strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION)), $acceptedFormats)) {
            $file = date("dmY") . "_" . date("GHi") . getFormattedTime() . "_news_img" . "." . pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION);
            $uploadfile = $uploaddir . $file;

            if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $uploadfile)) {

                $imgInsertResultSet = mysql_query("INSERT INTO newsimages(path, newsid) VALUES ('" . mysql_real_escape_string($file) . "', '" . mysql_real_escape_string($idNews) . "')") or die(mysql_error());
            } else echo $_FILES['images']['error'][$i];
        }
        $i++;
    }

}


if ($insertFlyResultSet && $mainImgInsertResultSet) {
    commitTransaction();
    echo "Success";
} else {
    rollbackTransaction();
    echo "Error";
}

redirect($_SERVER['HTTP_REFERER']);

?>